//
//  SynsViewController.m
//  Grammar
//
//  Created by Rick on 7/6/13.
//
//

#import "SynsViewController.h"
#import "AddNoteDataRequest.h"
#import "NoteBookManager.h"
#import "Note.h"
#import "GrammarManager.h"
#import "Grammar.h"
#import "ITTImageCacheManager.h"
#import "UpdateStudyPlanDataRequest.h"
#import "SyncStudyPlanDataRequest.h"
#import "SyncNoteBookDataRequest.h"

#define SYNC_NOTE_DATA_REQUEST  @"SYNC_NOTE_DATA_REQUEST"
#define ADD_NOTE_DATA_REQUEST   @"ADD_NOTE_DATA_REQUEST"
#define UPDATE_STUDY_PLAN_DATA_REQUEST      @"UPDATE_STUDY_PLAN_DATA_REQUEST"
#define SYNC_STUDY_PLAN_DATA_REQUEST        @"SYNC_STUDY_PLAN_DATA_REQUEST"

@interface SynsViewController ()
{
    NSMutableArray *_reviewGrammars;
    int _count;
}
@property (retain, nonatomic) IBOutlet UILabel *synsHintLabel;

@end

@implementation SynsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    [GrammarManager sharedManager].grammarType = @"review";
    _reviewGrammars =[[NSMutableArray alloc] initWithArray:[GrammarManager sharedManager].grammars];
    
    [GrammarManager sharedManager].grammarType = @"archive";
    [_reviewGrammars addObjectsFromArray:[GrammarManager sharedManager].grammars];
    
    _count = 0;
    for (Grammar *aGrammar in _reviewGrammars) {
        [NoteBookManager sharedManager].gramarId = aGrammar.grammarId;
        for (Note *aNote in [NoteBookManager sharedManager].notes) {
            if (aNote && [aNote.isSynced isEqualToString:@"1"]) {
                continue;
            }
            _count ++;
        }
    }
    _synsHintLabel.text = [NSString stringWithFormat:@"有[%d]条笔记需要同步，点击开始同步",_count];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_reviewGrammars release];
    [_synsHintLabel release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setSynsHintLabel:nil];
    [super viewDidUnload];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_NOTE_DATA_REQUEST object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:ADD_NOTE_DATA_REQUEST object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_STUDY_PLAN_DATA_REQUEST object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_STUDY_PLAN_DATA_REQUEST object:nil];
}
- (IBAction)tapSynsButton:(id)sender {
    NSString *uid = (NSString*)[[DataCacheManager sharedManager] getCachedObjectByKey:KEY_USER_ID];
    
    NSMutableDictionary *noteParameters = [NSMutableDictionary dictionary];
    [noteParameters setObject:uid forKey:@"uid"];
    [noteParameters setObject:@"0" forKey:@"noteWholeVersion"];
    //同步笔记接口
    [SyncNoteBookDataRequest requestWithParameters:noteParameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        for (NSDictionary *noteDic in [request.resultDic objectForKey:@"syncFind"]) {
            Note *aNote = [[Note alloc] initWithDataDic:noteDic];
            [NoteBookManager sharedManager].gramarId = aNote.grammarId;
            
            [GrammarManager sharedManager].grammarType = @"normal";
            NSMutableArray *noremalArray = [NSMutableArray arrayWithArray:[GrammarManager sharedManager].grammars];
            
            for (Grammar *aGrammar in noremalArray) {
                for (Grammar *theGrammar in _reviewGrammars) {
                    if ([theGrammar.grammarId isEqualToString:aGrammar.grammarId]) {
                        return ;
                    }
                }
                if ([aNote.grammarId isEqualToString:aGrammar.grammarId]) {
                    [GrammarManager sharedManager].grammarType = @"review";
                    [[GrammarManager sharedManager] addGrammar:aGrammar];
                }
            }
            
            aNote.isSynced = @"1";
            if ([aNote.notetype isEqualToString:@"1"]) {
                aNote.image = [NSString stringWithFormat:@"http://121.199.38.186/satgrammar/%@",aNote.content];
                aNote.content = @"";
            }
            [[NoteBookManager sharedManager] addNote:aNote];
        }
        
        for (NSDictionary *noteDic in [request.resultDic objectForKey:@"syncUpdate"]) {
            Note *aNote = [[Note alloc] initWithDataDic:noteDic];
            [NoteBookManager sharedManager].gramarId = aNote.grammarId;
            aNote.isSynced = @"1";
            [[NoteBookManager sharedManager] updateNote:aNote];
            [GrammarManager sharedManager].grammarType = @"normal";
            NSMutableArray *noremalArray = [NSMutableArray arrayWithArray:[GrammarManager sharedManager].grammars];
            
            for (Grammar *aGrammar in noremalArray) {
                if ([aNote.grammarId isEqualToString:aGrammar.grammarId]) {
                    [GrammarManager sharedManager].grammarType = @"review";
                    [[GrammarManager sharedManager] addGrammar:aGrammar];
                }
            }
        }
        
        for (NSDictionary *noteDic in [request.resultDic objectForKey:@"syncDelete"]) {
            Note *aNote = [[Note alloc] initWithDataDic:noteDic];
            [NoteBookManager sharedManager].gramarId = aNote.grammarId;
            [[NoteBookManager sharedManager] removeNote:aNote];
        }
     
    }onRequestCanceled:^(ITTBaseDataRequest *request) {
        
    }onRequestFailed:^(ITTBaseDataRequest *request) {
        
    }];
    
    
    [GrammarManager sharedManager].grammarType = @"review";
    for (Grammar *aGrammar in [GrammarManager sharedManager].grammars) {
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:uid forKey:@"uid"];
        [parameters setObject:aGrammar.grammarId forKey:@"studyPlanId"];
        [parameters setObject:@"0" forKey:@"state"];
        [UpdateStudyPlanDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
            [[DataCacheManager sharedManager] addObject:[request.resultDic objectForKey:@"studyPlanWholeVersion"] forKey:KEY_STUDY_WHOLE_VERSION];
        } onRequestCanceled:^(ITTBaseDataRequest *request) {
            
        } onRequestFailed:^(ITTBaseDataRequest *request) {
            
        }];
    }
    
    [GrammarManager sharedManager].grammarType = @"archive";
    for (Grammar *aGrammar in [GrammarManager sharedManager].grammars) {
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:uid forKey:@"uid"];
        [parameters setObject:aGrammar.grammarId forKey:@"studyPlanId"];
        [parameters setObject:@"1" forKey:@"state"];
        [UpdateStudyPlanDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
            [[DataCacheManager sharedManager] addObject:[request.resultDic objectForKey:@"studyPlanWholeVersion"] forKey:KEY_STUDY_WHOLE_VERSION];
            
        } onRequestCanceled:^(ITTBaseDataRequest *request) {
            
        } onRequestFailed:^(ITTBaseDataRequest *request) {
            
        }];
    }
//    if (_count == 0) {
//        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:nil message:@"没有需要同步的笔记哦" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alerView show];
//        [alerView release];
//        return;
//    }
    
    //添加笔记接口
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:uid forKey:@"uid"];
    for (Grammar *aGrammar in _reviewGrammars) {
        [NoteBookManager sharedManager].gramarId = aGrammar.grammarId;
        [parameters setObject:aGrammar.grammarId forKey:@"grammarId"];
        for (Note *aNote in [NoteBookManager sharedManager].notes) {
            if ([aNote.isSynced isEqualToString:@"1"]) {
                continue;
            }
            
            if (aNote.image && aNote.image.length > 0) {
                UIImage *image = [[ITTImageCacheManager sharedManager] getImageFromCacheWithUrl:aNote.image];
                [parameters setObject:image forKey:@"noteImage"];
                [parameters setObject:@"1" forKey:@"type"];
                [parameters setObject:aNote.noteCreateTimeStamp forKey:@"createTime"];
                
            }else {
                [parameters setObject:@"0" forKey:@"type"];
                [parameters setObject:aNote.noteCreateTimeStamp forKey:@"createTime"];
            }
            
            if (aNote.content && aNote.content.length > 0) {
                [parameters setObject:aNote.content forKey:@"content"];
            }
            
            [AddNoteDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
                [NoteBookManager sharedManager].gramarId = aGrammar.grammarId;
                aNote.isSynced = @"1";
                aNote.noteId = [request.resultDic objectForKey:@"noteId"];
                [[NoteBookManager sharedManager] updateNote:aNote];
                _count--;
                _synsHintLabel.text = [NSString stringWithFormat:@"有[%d]条笔记需要同步，点击开始同步",_count];
                if (_count == 0) {
                    UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:nil message:@"已经同步完笔记哦" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alerView show];
                    [alerView release];
                }
                
                //更新学习计划接口
                NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
                [parameters setObject:@"" forKey:@""];
                [UpdateStudyPlanDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
                    [[DataCacheManager sharedManager] addObject:[request.resultDic objectForKey:@"studyPlanWholeVersion"] forKey:KEY_STUDY_WHOLE_VERSION];
                } onRequestCanceled:^(ITTBaseDataRequest *request) {
                    
                } onRequestFailed:^(ITTBaseDataRequest *request) {
                    
                }];
            } onRequestCanceled:^(ITTBaseDataRequest *request) {
                
            } onRequestFailed:^(ITTBaseDataRequest *request) {
                
            }];
            
            
        }
    }
    
    [self syncStudyPlanDataRequest];
}
- (void)syncStudyPlanDataRequest
{
    //同步学习计划接口
    NSString *uid = (NSString*)[[DataCacheManager sharedManager] getCachedObjectByKey:KEY_USER_ID];
    NSString *wholeStudyVersion = (NSString*)[[DataCacheManager sharedManager] getCachedObjectByKey:KEY_STUDY_WHOLE_VERSION];
    if (wholeStudyVersion && wholeStudyVersion.length > 0) {
    
    }else {
        wholeStudyVersion = @"1";
    }
    [GrammarManager sharedManager].grammarType = @"normal";
    NSMutableArray *noremalArray = [NSMutableArray arrayWithArray:[GrammarManager sharedManager].grammars];
    
    NSMutableDictionary *syncStudyParameters = [NSMutableDictionary dictionary];
    [syncStudyParameters setObject:uid forKey:@"uid"];
    [syncStudyParameters setObject:wholeStudyVersion forKey:@"studyPlanWholeVersion"];
    [SyncStudyPlanDataRequest requestWithParameters:syncStudyParameters withIndicatorView:nil withCancelSubject:nil onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        for (NSDictionary *studyDic in [request.resultDic objectForKey:@"syncUpdate"]) {
            if ([[studyDic objectForKey:@"state"] isEqualToString:@"0"]) {
                
                for (Grammar *aGrammar in noremalArray) {
                    if ([aGrammar.grammarId isEqualToString:[studyDic objectForKey:@"grammarId"]]) {
                        [GrammarManager sharedManager].grammarType = @"review";
                        [[GrammarManager sharedManager] addGrammar:aGrammar];
                    }
                }
            }else if([[studyDic objectForKey:@"state"] isEqualToString:@"1"]) {
                for (Grammar *aGrammar in noremalArray) {
                    if ([aGrammar.grammarId isEqualToString:[studyDic objectForKey:@"grammarId"]]) {
                        [GrammarManager sharedManager].grammarType = @"archive";
                        [[GrammarManager sharedManager] addGrammar:aGrammar];
                    }
                }
                
            }
            
        }
        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:nil message:@"同步完成" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alerView show];
        [alerView release];
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        
    }];

}
- (IBAction)tapBackButton:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
@end
